import React, { useContext } from 'react';
import { Card, Row, Col } from 'antd';
import { SerialContext } from '../context/SerialContext';
import './ServoErrorStatusComponent.css';

const errorDefinitions = [
  { bit: 64, label: '指令错误', description: '无效指令或参数，请检查协议。' },
  { bit: 32, label: '过载', description: '舵机负载过大，可能卡死或受阻。' },
  { bit: 16, label: '校验和错误', description: '数据传输出现校验错误，请重试。' },
  { bit: 8, label: '指令超范围', description: '发送的指令参数超出舵机支持范围。' },
  { bit: 4, label: '过热', description: '舵机温度过高，请等待散热。' },
  { bit: 2, label: '角度超范围', description: '舵机目标角度超出允许范围。' },
  { bit: 1, label: '过压欠压', description: '电源电压异常，请检查供电。' },
  { bit: 128, label: '数据包长度无效', description: '接收到的数据包长度不符合规范。' },
  { bit: 256, label: '无效数据', description: '数据内容格式错误或数据损坏。' },
];

const ServoErrorStatusComponent: React.FC = () => {
  const ctx = useContext(SerialContext);
  if (!ctx) return null;

  const { servoModel } = ctx;
  const { inside_error } = servoModel;

  return (
    <Card title="舵机状态" bordered={false} className="servo-error-card">
      <Row>
        <Col span={24}>
          {errorDefinitions.map(({ bit, label, description }) => {
            const isError = (inside_error & bit) !== 0;
            return (
              <div
                key={bit}
                className={`error-item ${isError ? 'error' : 'normal'}`}
              >
                <div className="error-label">{label}</div>
                <div className="error-desc">{description}</div>
              </div>
            );
          })}
        </Col>
      </Row>
    </Card>
  );
};

export default ServoErrorStatusComponent;
